<?php
namespace app\admin\controller;

use think\Image;
use think\Request;
use app\admin\model\User as UserModel;
class User extends Common{
    protected $request;
    protected $user;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->request=Request::instance();
        $this->user=new UserModel();
    }
    public function index(){
        $users=$this->user->getAll();
        $this->assign('users',$users);
        return $this->fetch();
    }
    public function editeUser(){
        $id=input('user_id');
        if($this->request->isGet()){

            $user=$this->user->getOne(['user_id'=>$id]);
            $this->assign('user',$user);
            return $this->fetch();
        }else{
            $data=$this->request->post();
            $res=$this->user->saveData(['user_id'=>$id],$data);
            if($res){
                $this->success('编辑用户信息成功','user/index');

            }else{
                $this->error('编辑用户信息失败','user/editeuser?user_id='.$id);
            }
        }
    }
    public function delUser(){
        $id=input('id');
        $res=$this->user->delData(['user_id'=>$id]);
        if ($res) {
            return json([
                'status' => 1,
                'msg' => '删除成功'
            ]);
        }else{
            return json([
                'status' => 0,
                'msg' => '删除失败'
            ]);
        }
    }
    public function uploadImg()
    {

        $file = $this->request->file('file_data');
        //原图保存路径
        $path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'user';
        $info = $file->move($path);
        //缩略图名称
        $thumb_name = 'thumb_' . $info->getFilename();
        //缩略图保存路径和文件名称
        $thumb_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'user ' . DS . 'thumb' . DS . $thumb_name;
        if ($info) {
            //缩略图
            $image = Image::open($this->request->file('file_data'));
            $image->thumb(200, 200, Image::THUMB_CENTER)->save($thumb_path);
            return json([
                'status' => 1,
                'path' => $info->getSaveName(),
                'thumb' => 'thumb' . DS . $thumb_name
            ]);
        } else {
            return json([
                'status' => 0,
                'err' => $file->getError()
            ]);
        }
    }
}